package com.example.service;

import com.example.entity.*;
import com.example.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderService {
    private final VehicleService vehicleService;
    private final FareCalculator fareCalculator;
    private final OrderRepository orderRepository;
    private final VehicleRepository vehicleRepository;

    @Autowired
    public OrderService(VehicleService vehicleService, FareCalculator fareCalculator, OrderRepository orderRepository, VehicleRepository vehicleRepository) {
        this.vehicleService = vehicleService;
        this.fareCalculator = fareCalculator;
        this.orderRepository = orderRepository;
        this.vehicleRepository = vehicleRepository;
    }

    public Order createOrder(String passenger, OrderType type,
                             double startLat, double startLng,
                             double endLat, double endLng) {
        return createOrder(passenger, type, startLat, startLng, endLat, endLng, 0, 0);
    }

    public Order createOrder(String passenger, OrderType type,
                             double startLat, double startLng,
                             double endLat, double endLng,
                             double distance, int duration) {
        Order order = new Order();
        order.setType(type);
        System.out.println("OrderService类：创建订单时：Order type: " + type);
        order.setPassengerName(passenger);
        order.setStartLat(startLat);
        order.setStartLng(startLng);
        order.setEndLat(endLat);
        order.setEndLng(endLng);
        order.setCreatedAt(LocalDateTime.now());
        order.setStartTime(LocalDateTime.now());
        
        // 设置距离和时长
        if (distance > 0) {
            order.setDistance(distance);
        } else {
            // 使用直线距离进行估算
            double earthRadius = 6371; // 地球半径，单位公里
            double dLat = Math.toRadians(endLat - startLat);
            double dLng = Math.toRadians(endLng - startLng);
            double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                       Math.cos(Math.toRadians(startLat)) * Math.cos(Math.toRadians(endLat)) *
                       Math.sin(dLng / 2) * Math.sin(dLng / 2);
            double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            double estimatedDistance = earthRadius * c;
            order.setDistance(estimatedDistance);
        }
        
        if (duration > 0) {
            order.setDuration(duration);
        } else {
            // 假设平均速度为30km/h
            order.setDuration((int)(order.getDistance() * 60 / 30)); // 分钟
        }

        Vehicle vehicle = dispatchVehicle(order);
        if (vehicle == null) {
            return null;
        }
        order.setAssignedVehicle(vehicle);
        calculateFare(order);
        order.setId(generateOrderId());
        order.setStatus(OrderStatus.ACCEPTED);
        vehicleService.markVehicleONTRIP(vehicle);

        // 模拟行程结束
        simulateTripEnd(order);

        orderRepository.save(order);
        return order;
    }

    private String generateOrderId() {
        return UUID.randomUUID().toString();
    }

    private Vehicle dispatchVehicle(Order order) {
        System.out.println("OrderService类：分配车辆时：Order type: " + order.getType());
        List<Vehicle> candidates = vehicleService.getAvailableVehicles(order.getType());

        if (candidates.isEmpty()) {
            return null;
        }

        // 优先匹配最近的车辆
        return candidates.stream()
                .min((v1, v2) -> Double.compare(
                        v1.calculateDistance(order.getAssignedVehicle()),
                        v2.calculateDistance(order.getAssignedVehicle())
                )).orElse(null);
    }

    private void calculateFare(Order order) {
        double fare = fareCalculator.calculate(order);
        order.setTotalFare(fare);
        
        // 计算公司抽成
        Vehicle vehicle = order.getAssignedVehicle();
        if (vehicle != null) {
            double commission = fareCalculator.calculateCommission(order, vehicle);
            order.setCommission(commission);
        }
    }


    public void updateOrderStatus(String orderId, OrderStatus newStatus) {
        Order order = orderRepository.findById(orderId).orElse(null);
        if (order != null) {
            order.setStatus(newStatus);
            orderRepository.save(order);
        }
    }

    private void simulateTripEnd(Order order) {
        Random random = new Random();
        int delaySeconds = random.nextInt(31) + 30; // 随机 30 到 60 秒
        new java.util.Timer().schedule(
                new java.util.TimerTask() {
                    @Override
                    public void run() {
                        order.setStatus(OrderStatus.COMPLETED);
                        order.setEndTime(LocalDateTime.now());
                        orderRepository.save(order);
                        vehicleService.markVehicleAvailable(order.getAssignedVehicle());
                    }
                },
                delaySeconds * 1000
        );
    }

    public Order getOrderById(String orderId) {
        return orderRepository.findById(orderId).orElse(null);
    }
    
    /**
     * 获取指定用户的所有订单
     * @param userId 用户ID
     * @return 该用户的订单列表
     */
    public List<Order> getOrdersByUserId(String userId) {
        // 这里假设Order对象有一个关联的用户字段，或者passengerName字段匹配用户名
        // 实际实现可能需要根据真实的数据模型来调整
        return orderRepository.findAll().stream()
                .filter(order -> userId.equals(order.getPassengerName())) // 假设使用passengerName作为匹配条件
                .collect(Collectors.toList());
    }
    
    /**
     * 获取系统中的所有订单
     * @return 所有订单的列表
     */
    public List<Order> getAllOrders() {
        return orderRepository.findAll();
    }

}